<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { HandCardAssetApi } from '#/api/spa/handcard/asset';

import { Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';

import { Input, Modal, message } from 'ant-design-vue';
import { createVNode, ref } from 'vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteHandCardAsset,
  exportHandCardAsset,
  getHandCardAssetPage,
} from '#/api/spa/handcard/asset';
import { openHandCard, recallHandCard, actionHandCard, changeStatusHandCard, mergeHandCard } from '#/api/spa/handcard/asset/action';
// import {ref, computed} from 'vue';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import ConsumeModal from './modules/ConsumeModal.vue';
import Form from './modules/form.vue';
import HandCardImportModal from '../../hand-card-status/components/HandCardImportModal.vue';

// 简单的防抖函数
function debounce<T extends (...args: any[]) => any>(func: T, wait: number): T {
  let timeout: NodeJS.Timeout | null = null;
  return ((...args: any[]) => {
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), wait);
  }) as T;
}

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

const [ConsumeModalComponent, consumeModalApi] = useVbenModal({
  connectedComponent: ConsumeModal,
  destroyOnClose: true,
});

const [HandCardImportModalTrigger, handCardImportModalApi] = useVbenModal({
  connectedComponent: HandCardImportModal,
  destroyOnClose: true,
});

// 开卡中的手牌集合，防止重复点击
const openingIds = ref<Set<number>>(new Set());

/** 刷新表格 */
function onRefresh() {
  gridApi.query();
}

/** 创建手牌资产 */
function handleCreate() {
  formModalApi.setData({}).open();
}

/** 编辑手牌资产 */
function handleEdit(row: HandCardAssetApi.HandCardAsset) {
  formModalApi.setData(row).open();
}

// 开牌函数（带防抖）
const handleOpenCard = debounce(async (row: HandCardAssetApi.HandCardAsset) => {
  const cardId = row.id as number;
  if (openingIds.value.has(cardId)) {
    message.warning('该手牌正在开卡中，请稍候');
    return;
  }
  openingIds.value.add(cardId);
  const msgKey = `open_card_${cardId}`;
  const hide = message.loading({ content: '开卡中...', key: msgKey });
  try {
    await openHandCard(cardId);
    message.success({ content: `手牌 ${row.cardNumber || cardId} 开卡成功`, key: msgKey });
    onRefresh();
  } finally {
    hide();
    openingIds.value.delete(cardId);
  }
}, 500);

/** 撤销开卡 */
const handleRecall = debounce(async (row: HandCardAssetApi.HandCardAsset) => {
  const hide = message.loading({ content: '撤销中...', key: 'recall_card' });
  try {
    await recallHandCard(row.id as number);
    message.success({ content: `手牌 ${row.cardNumber || row.id} 撤销成功`, key: 'recall_card' });
    onRefresh();
  } finally {
    hide();
  }
}, 500);

/** 通用动作 */
function handleGenericAction(row: HandCardAssetApi.HandCardAsset) {
  const actionEnumRef = ref('OPEN');
  Modal.confirm({
    title: '执行通用动作',
    content: () =>
      createVNode('div', { class: 'space-y-2' }, [
        createVNode('div', null, `手牌：${row.cardNumber || row.id}`),
        createVNode(Input, {
          value: actionEnumRef.value,
          placeholder: '请输入动作枚举，如 OPEN/RECALL/CHANGE_STATUS/…',
          'onUpdate:value': (v: string) => (actionEnumRef.value = v),
        }),
      ]),
    onOk: async () => {
      const hide = message.loading({ content: '执行中...', key: 'action_card' });
      try {
        await actionHandCard({ cardId: row.id as number, actionEnum: actionEnumRef.value });
        message.success({ content: '执行成功', key: 'action_card' });
        onRefresh();
      } finally {
        hide();
      }
    },
  });
}

/** 修改状态 */
function handleChangeStatus(row: HandCardAssetApi.HandCardAsset) {
  const statusRef = ref('');
  Modal.confirm({
    title: '修改状态',
    content: () =>
      createVNode('div', { class: 'space-y-2' }, [
        createVNode('div', null, `手牌：${row.cardNumber || row.id}`),
        createVNode(Input, {
          value: statusRef.value,
          placeholder: '请输入新状态，如 MAINTENANCE/IDLE/…',
          'onUpdate:value': (v: string) => (statusRef.value = v),
        }),
      ]),
    onOk: async () => {
      const hide = message.loading({ content: '提交中...', key: 'change_status' });
      try {
        await changeStatusHandCard({ cardId: row.id as number, newStatus: statusRef.value });
        message.success({ content: '状态修改成功', key: 'change_status' });
        onRefresh();
      } finally {
        hide();
      }
    },
  });
}

/** 合并手牌 */
function handleMerge(row: HandCardAssetApi.HandCardAsset) {
  const sourceRef = ref<number | null>((row.id as number) || null);
  const targetRef = ref<number | null>(null);
  Modal.confirm({
    title: '合并手牌',
    content: () =>
      createVNode('div', { class: 'space-y-2' }, [
        createVNode(Input, {
          value: String(sourceRef.value ?? ''),
          placeholder: '来源手牌ID',
          'onUpdate:value': (v: string) => (sourceRef.value = v ? Number(v) : null),
        }),
        createVNode(Input, {
          value: String(targetRef.value ?? ''),
          placeholder: '目标手牌ID',
          'onUpdate:value': (v: string) => (targetRef.value = v ? Number(v) : null),
        }),
      ]),
    onOk: async () => {
      if (!sourceRef.value || !targetRef.value) {
        message.warning('请填写来源与目标手牌ID');
        return Promise.reject();
      }
      const hide = message.loading({ content: '合并中...', key: 'merge_card' });
      try {
        await mergeHandCard({ sourceCardId: sourceRef.value, targetCardId: targetRef.value });
        message.success({ content: '合并成功', key: 'merge_card' });
        onRefresh();
      } finally {
        hide();
      }
    },
  });
}

/** 消费手牌资产 */
function handleConsume(row: HandCardAssetApi.HandCardAsset) {
  consumeModalApi.setData({ handCardInfo: row }).open();
}

/** 删除手牌资产 */
async function handleDelete(row: HandCardAssetApi.HandCardAsset) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    key: 'action_key_msg',
  });
  try {
    await deleteHandCardAsset(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
      key: 'action_key_msg',
    });
    onRefresh();
  } finally {
    hideLoading();
  }
}

/** 导出表格 */
async function handleExport() {
  const data = await exportHandCardAsset(await gridApi.formApi.getValues());
  downloadFileFromBlobPart({ fileName: '手牌资产.xls', source: data });
}

/** 批量导入手牌 */
function handleImport() {
  handCardImportModalApi.open();
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    columns: useGridColumns(),
    height: 'auto',
    pagerConfig: {
      enabled: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getHandCardAssetPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<HandCardAssetApi.HandCardAsset>,
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="onRefresh" />
    <ConsumeModalComponent @success="onRefresh" />

    <Grid table-title="手牌资产列表">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: $t('ui.actionTitle.create', ['手牌资产']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['spa:hand-card-asset:create'],
              onClick: handleCreate,
            },
            {
              label: $t('ui.actionTitle.export'),
              type: 'primary',
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['spa:hand-card-asset:export'],
              onClick: handleExport,
            },
            {
              label: '批量导入',
              type: 'primary',
              icon: ACTION_ICON.UPLOAD,
              auth: ['spa:hand-card-asset:create'],
              onClick: handleImport,
            },
          ]"
        />
      </template>
      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: $t('spa.handCard.openCard'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['spa:hand-card-asset:update'],
              onClick: handleOpenCard.bind(null, row),
              tooltip: `${$t('spa.handCard.handCardNumber')}: ${row.cardNumber || row.id || $t('spa.handCard.unknown')}`,
            },
            {
              label: $t('spa.handCard.consume'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['spa:hand-card-asset:update'],
              onClick: handleConsume.bind(null, row),
              tooltip: `消费 - ${$t('spa.handCard.handCardNumber')}: ${row.cardNumber || row.id || $t('spa.handCard.unknown')}`,
            },
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['spa:hand-card-asset:update'],
              onClick: handleEdit.bind(null, row),
              tooltip: `编辑 - ${$t('spa.handCard.handCardNumber')}: ${row.cardNumber || row.id || $t('spa.handCard.unknown')}`,
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              icon: ACTION_ICON.DELETE,
              auth: ['spa:hand-card-asset:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.id]),
                confirm: handleDelete.bind(null, row),
              },
              tooltip: `删除 - ${$t('spa.handCard.handCardNumber')}: ${row.cardNumber || row.id || $t('spa.handCard.unknown')}`,
            },
          ]"
          :dropDownActions="[
            {
              label: '撤销',
              type: 'link',
              // icon: ACTION_ICON.EDIT,
              auth: ['spa:hand-card-asset:update'],
              onClick: handleRecall.bind(null, row),
            },
            {
              label: '通用动作',
              type: 'link',
              // icon: ACTION_ICON.EDIT,
              auth: ['spa:hand-card-asset:update'],
              onClick: handleGenericAction.bind(null, row),
            },
            {
              label: '修改状态',
              type: 'link',
              // icon: ACTION_ICON.EDIT,
              auth: ['spa:hand-card-asset:update'],
              onClick: handleChangeStatus.bind(null, row),
            },
            {
              label: '合并',
              type: 'link',
              // icon: ACTION_ICON.EDIT,
              auth: ['spa:hand-card-asset:update'],
              onClick: handleMerge.bind(null, row),
            },
          ]"
        />
      </template>
    </Grid>
    <HandCardImportModalTrigger @success="onRefresh" />
  </Page>
</template>
